
Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports _2bMatesSite.BO

Namespace _2bMatesSite
	''' <summary>
	''' Summary description for _default.
	''' </summary>
	Public Partial Class _default
		Inherits System.Web.UI.Page
		Protected btnJoin As System.Web.UI.WebControls.Button
		Protected cssFileName As String
		Public blankImagesCount As Integer = 0
		Protected sSpecialPageTypeIDParam As String = Constants.SPECIAL_PAGE_TYPE_ID_PARAM
		Protected hlHeaderRank As System.Web.UI.WebControls.HyperLink
		Protected hlHeaderMessages As System.Web.UI.WebControls.HyperLink


		Public Property LoggedUser() As BO.User
			Get
				' Retrieve the logged-in user, by it's ID, stored in the sesion object
				Return Common.Utils.GetLoggedUser(Session)
			End Get

			Set
				If value = Nothing Then
					' Logout
					Session(Constants.ssnUserID) = Nothing
					Session.Abandon()
				Else
					' Login
					Session(Constants.ssnUserID) = value.ID

					' Add the session state to the global cache
					'
					' NOTE: only if the user allows viewing his
					' online status.
					'
					' Changing this setting of the user would take
					' effect next time he logs-in
					'
					If value.ShowOnline Then
						Constants.SESSIONS(Session.SessionID) = Session
						Constants.LOGGED_USERS_IDS(value.ID) = value
					End If

					' Init search filter used when users are not logged to null
					Session(Constants.ssnSearch_ViewDetailsNotLogged) = Nothing
				End If
			End Set
		End Property

		Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
			' init page from xml file
			Dim bwp As New BaseWebPage()
			bwp.initPageTitles(Constants.[DEFAULT], "", Nothing, Me.Page, Nothing)
			bwp.initAdvertisements(Nothing, Me.Page)

			If Constants.SHOW_GAMES <> Constants.SHOW_ON Then
				hlHeaderGames.Visible = False
				litHeaderMenuSpaceGames.Visible = False
			Else
				hlHeaderGames.Visible = True
				litHeaderMenuSpaceGames.Visible = True
			End If

			If Constants.SHOW_MUSIC <> Constants.SHOW_ON Then
				hlHeaderMusic.Visible = False
				litHeaderMenuSpaceMusic.Visible = False
			Else
				litHeaderMenuSpaceMusic.Visible = True
				'init music link
				Dim musicID As String = "-1"
				Dim music As BO.SpecialPage = BO.SpecialPages.GetSpecialPageByName(Constants.MUSIC_PAGE)
				If music <> Nothing Then
					musicID = music.ID.ToString()
				End If

				'hlHeaderMusic.NavigateUrl = "../" + Constants.MUSIC_PAGE + "?" + SPECIAL_PAGE_TYPE_ID_PARAM + "=" + musicID;
				hlHeaderMusic.NavigateUrl = Constants.SPECIAL + "?" + "typeID" + "=" + musicID
			End If
			' Put user code to initialize the page here
			cssFileName = Constants.CSS_DEAFULT_FILE_NAME

			'btnLogin.Attributes.Add("onMouseOver", "this.src='images/login_over.gif'");
			'btnLogin.Attributes.Add("onMouseOut", "this.src='images/login.gif'");

			If Constants.SHOW_GROUPS <> Constants.SHOW_ON Then
				trFeaturedGroup.Visible = False
				hlHeaderGroups.Visible = False
				litHeaderMenuSpaceGroups.Visible = False
			Else
				hlHeaderGroups.Visible = True
				litHeaderMenuSpaceGroups.Visible = True
				'init featured group
				Dim grp As Group = Groups.GetFeaturedGroup()

				If grp <> Nothing Then
					Dim grpPicture As GroupPicture = grp.DefaultPicture
					If grpPicture <> Nothing Then
						hlFeaturedGroupPhoto.ImageUrl = Pictures.GetPictureSrcFullURL(grp.DefaultPicture, True, "")
					Else
						hlFeaturedGroupPhoto.ImageUrl = "images/default_thumbnail.gif"
					End If
					hlFeaturedGroupPhoto.ToolTip = grp.Name
					hlFeaturedGroupPhoto.NavigateUrl = Constants.GROUP + "?" + Constants.GROUP_PARAM + "=" + grp.ID
					hlFeaturedGroupName.Text = grp.Name
					hlFeaturedGroupName.NavigateUrl = Constants.GROUP + "?" + Constants.GROUP_PARAM + "=" + grp.ID

					hlFeaturedGroupCategory.Text = Constants.CATEGORIES.GetCategoryByID(grp.CatID).Name
					hlFeaturedGroupCategory.NavigateUrl = Constants.CATEGORY_GROUPS + "?" + Constants.CATEGORY_PARAM + "=" + grp.CatID

					If grp.ShortAbout <> Nothing AndAlso grp.ShortAbout.Length > 0 Then
						lblFeaturedGroupAbout.Text = Server.HtmlEncode(getBeginning(grp.ShortAbout, Constants.MAX_GROUP_HOME_ABOUT_LENGTH))
					Else
						lblFeaturedGroupAbout.Text = "&nbsp;"
					End If
				Else
					trFeaturedGroup.Visible = False
				End If
			End If

			' init random user
			'			ArrayList arrRandomUsers = Users.FindRandomUsersWithSongURL(1);
			'			if ( arrRandomUsers.Count > 0 )
			'				{
			'				User uRandomUser = (User) arrRandomUsers[0];
			'				UserPicture pic = uRandomUser.DefaultPicture;
			'				hlRandomGroupName.NavigateUrl = Constants.MEMBERS + "?id=" + uRandomUser.ID;
			'				hlRandomGroupName.Text = uRandomUser.Name;
			'				hlRandomGroupImage.NavigateUrl = Constants.MEMBERS + "?id=" + uRandomUser.ID;
			'					hlRandomGroupImage.ImageUrl = Pictures.GetPictureSrcFullURL(pic, true, "");
			'				}
			'				else
			'				{
			'					hlRandomGroupName.Visible = false;
			'					hlRandomGroupImage.Visible = false;
			'				}

			' NOTE: Uncomment this when there are groups with bands

			' init random group
			Dim arrRandomGroups As ArrayList = Groups.FindRandomGroupsWithBands(1)
			If arrRandomGroups.Count > 0 Then
				Dim gRandomGroup As Group = DirectCast(arrRandomGroups(0), Group)
				Dim pic As GroupPicture = gRandomGroup.DefaultPicture
				hlRandomGroupName.NavigateUrl = Constants.GROUP + "?" + Constants.GROUP_PARAM + "=" + gRandomGroup.ID
				hlRandomGroupName.Text = gRandomGroup.Name
				hlRandomGroupImage.NavigateUrl = Constants.GROUP + "?" + Constants.GROUP_PARAM + "=" + gRandomGroup.ID
				hlRandomGroupImage.ImageUrl = Pictures.GetPictureSrcFullURL(pic, True, "")
				hlRandomGroupImage.ToolTip = gRandomGroup.Name
			Else
				hlRandomGroupName.Visible = False
				hlRandomGroupImage.Visible = False
			End If

			If Not IsPostBack Then
				If Request.Cookies(Constants.cookiePassword) <> Nothing AndAlso Request.Cookies(Constants.cookieEmail) <> Nothing Then
					Dim cookieEmail As String = Request.Cookies(Constants.cookieEmail).Value
					Dim cookiePass As String = Request.Cookies(Constants.cookiePassword).Value
					Dim usr As User = Users.Login(cookieEmail, cookiePass)

					If usr <> Nothing Then
						' upon success save the user ID in the session and redirect to his home page
						usr.Save()
						LoggedUser = usr

						Response.Redirect(Constants.WELCOME)
					End If
				End If

				BindList()
			End If
			CreateReditToPageJS()
		End Sub

		#region Web Form Designer generated code
		Protected Overloads Overrides Sub OnInit(ByVal e As EventArgs)
			'
			' CODEGEN: This call is required by the ASP.NET Web Form Designer.
			'
			InitializeComponent()
			MyBase.OnInit(e)
		End Sub

		''' <summary>
		''' Required method for Designer support - do not modify
		''' the contents of this method with the code editor.
		''' </summary>
		Private Sub InitializeComponent()

		End Sub
#End Region

		Public Function CreateDataSource() As ICollection
			'BO.User usr = LoggedUser;

			Dim startIndex As Integer = 0
			Dim endIndex As Integer = startIndex + 3

			Dim i As Integer
			Dim dt As New DataTable()
			Dim dr As DataRow

			dt.Columns.Add(New DataColumn("ImageURL", GetType(String)))
			dt.Columns.Add(New DataColumn("Name", GetType(String)))
			dt.Columns.Add(New DataColumn("OnlineImg", GetType(String)))
			dt.Columns.Add(New DataColumn("FriendID", GetType(String)))
			dt.Columns.Add(New DataColumn("MemberURL", GetType(String)))
			dt.Columns.Add(New DataColumn("FullName", GetType(String)))

			Dim temp As UserPicture
			Dim imagesOnLastRow As Integer = 0
			Dim t As Integer = 0
			Dim counter As Integer = 0
			Dim FriendsCount As Integer
			blankImagesCount = 0
			Dim LoggedUsersList As ArrayList = Common.Utils.GetLoggedUsersIDs()

			Dim usrNetworkedUsers As ArrayList = Users.GetRandomUsers(3, True)

			FriendsCount = usrNetworkedUsers.Count

			endIndex = Math.Min(endIndex, FriendsCount)
			t = (endIndex - startIndex)
			Math.DivRem(t, 3, imagesOnLastRow)
			counter = 0

			For Each nf As BO.User In usrNetworkedUsers
				If counter >= startIndex AndAlso counter < endIndex Then
					dr = dt.NewRow()
					temp = nf.DefaultPicture
					If temp <> Nothing Then
						dr(0) = Pictures.GetPictureSrcFullURL(temp, True, "")
					Else
						dr(0) = "images/default_thumbnail.gif"
					End If
					dr(1) = getNameBeginning(nf.Name)
					If LoggedUsersList.Contains(nf.ID) Then
						dr(2) = "images/online_status.gif"
					Else
						dr(2) = "images/spacer.gif"
					End If
					dr(3) = nf.ID
					dr(4) = Constants.MEMBERS + "?id=" + nf.ID
					dr(5) = nf.Name
					dt.Rows.Add(dr)
				End If
				System.Math.Max(System.Threading.Interlocked.Increment(counter),counter - 1)
			Next

			If imagesOnLastRow <> 0 Then
				blankImagesCount = 3 - imagesOnLastRow
				i = imagesOnLastRow
				While i < 3
					dr = dt.NewRow()
					dr(0) = "images/spacer.gif"
					dr(1) = ""
					dr(2) = "images/spacer.gif"
					dt.Rows.Add(dr)
					System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
				End While
			End If

			Dim dv As New DataView(dt)
			Return dv
		End Function

		Public Sub BindList()
			Dim itemsCount As Integer
			Dim blankImageIndex As Integer
			Dim i As Integer

			dlNewPeople.DataSource = CreateDataSource()
			dlNewPeople.DataBind()

			itemsCount = dlNewPeople.Items.Count
			blankImageIndex = itemsCount - blankImagesCount
			i = 0
			i = blankImageIndex
			While i < itemsCount
				(DirectCast(dlNewPeople.Items(i).FindControl("hlName"), System.Web.UI.WebControls.HyperLink)).CssClass = "empty_image"
				(DirectCast(dlNewPeople.Items(i).FindControl("hlPhoto"), System.Web.UI.WebControls.HyperLink)).CssClass = "empty_image"
				System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
			End While
		End Sub

		Public Function getNameBeginning(ByVal name As String) As String
			If name.Length > Constants.MAX_NAME_LENGTH_ABOVE_IMAGE Then
				Return (name.Substring(0, Constants.MAX_NAME_LENGTH_ABOVE_IMAGE) + "...")
			End If

			Return name
		End Function

		Public Function getBeginning(ByVal text As String, ByVal length As Integer) As String
			If text.Length > length Then
				Return (text.Substring(0, length) + "...")
			End If
			Return text
		End Function

		Protected Sub btnLogin_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			If Request.Params(chkRemember.UniqueID) = "on" Then
				Response.Cookies(Constants.cookieEmail).Expires = DateTime.MaxValue
				Response.Cookies(Constants.cookiePassword).Expires = DateTime.MaxValue
				Response.Cookies(Constants.cookieEmail).Value = txtEmail.Text.Trim()
				Response.Cookies(Constants.cookiePassword).Value = pswPassword.Text.Trim()
			End If

			Dim usr As User = Users.Login(txtEmail.Text, pswPassword.Text)

			If usr <> Nothing Then
				' upon success save the user ID in the session and redirect to his home page
				usr.Save()
				LoggedUser = usr

				Response.Redirect(Constants.WELCOME)
			Else
				Session.Add("usr_pass", pswPassword.Text.Trim())
				Session("usr_pass") = pswPassword.Text.Trim()
				Dim isPasswordEntered As Boolean = (pswPassword.Text.Trim() = "")
				Response.Redirect(Constants.LOGIN_PAGE + "?usr=" + Server.UrlEncode(txtEmail.Text.Trim()) + "&pass=" + isPasswordEntered)
			End If
		End Sub

		Protected Sub btnSignUp_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Response.Redirect(Constants.JOIN)
		End Sub
		Public Sub CreateReditToPageJS()
			Response.Write("<script><!--" & Chr(10) & "")
			Response.Write("var arrRedirToPage = new Array();" & Chr(10) & "")

			'			if (Common.Utils.GetLoggedUser( Session )==null) 
			'			{
			'				Response.Write("arrRedirToPage = null;\n");
			'			} 
			'			else 
			'			{
			Constants.SPECIALPAGES = New BO.SpecialPages()
			Dim specialPagesCount As Integer = Constants.SPECIALPAGES.List.Count
			Dim tmpSpecialPage As BO.SpecialPage

			Dim i As Integer
			Dim pageTypeID As Integer = -1
			Dim isSelected As String = "false"

			If Request.Params(Constants.SPECIAL_PAGE_TYPE_ID_PARAM) <> Nothing AndAlso Request.Params(Constants.SPECIAL_PAGE_TYPE_ID_PARAM) <> "" Then
				pageTypeID = Convert.ToInt32(Request.Params(Constants.SPECIAL_PAGE_TYPE_ID_PARAM))
			End If

			i = 0
			While i < specialPagesCount
				tmpSpecialPage = DirectCast(Constants.SPECIALPAGES.List(i), BO.SpecialPage)
				isSelected = "false"
				If pageTypeID = tmpSpecialPage.ID Then
					isSelected = "true"
				End If
				Response.Write("arrRedirToPage[arrRedirToPage.length] = new Array('" + tmpSpecialPage.Name + "', '" + tmpSpecialPage.ID.ToString() + "', '" + isSelected + "');" & Chr(10) & "")
				System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
			End While
			'			}
			Response.Write("" & Chr(10) & "--></script>" & Chr(10) & "")
		End Sub
	End Class
End Namespace






